package com.example.music.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.music.model.User;
import com.example.music.service.UserService;
import com.example.music.util.Constant;
import com.example.music.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * ClassName: UserController
 * Package: com.example.music.controller
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-04-11
 * Time: 15:23
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    //登录逻辑
    @PostMapping("/login")
    public Result<User> login(User user, HttpServletRequest request){
        //查询条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,user.getUsername());
        //首先去查找用户名是否存在
        User user1 = userService.getOne(queryWrapper);
        if (user1 == null){
            return new Result(-1,"用户名或密码错误",null);
        }
        //若是用户名存在 密码对比 使用BCrypt加密 在启动类加上注解
        Boolean ret = bCryptPasswordEncoder.matches(user.getPassword(),user1.getPassword());
        if (!ret){
            return new Result<>(-1,"用户名或密码错误",null);
        }
        //存入会话  1.创建了Session会话 传给客户端一个cookie
        // 2.setAttribute作用是将要用到的数据 存入Session域当中 方便在其他地方获取到
        request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user1);
        return new Result(0,"登录成功",user1);
    }

}
